package com.netwit.common.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;

@Configuration
@MapperScan(basePackages={"com.netwit.common.mapper"}, sqlSessionFactoryRef="dynamicSqlSessionFactory")
public class DynamicDbConfig {
    private static String MYBATIS_CONFIG = "mybatis-config.xml";
    private static String MAPPER_PATH = "mapper/*.xml";

    @Bean
    public SqlSessionFactoryBean dynamicSqlSessionFactory(@Qualifier("lazyDataSource")LazyConnectionDataSourceProxy proxy) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + MAPPER_PATH;
        sqlSessionFactory.setMapperLocations(resolver.getResources(packageSearchPath));
        sqlSessionFactory.setDataSource(proxy);
        return sqlSessionFactory;
    }

}